package com.wan.setting;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.setting.Setting;

public class Conf extends Setting{
    private static final String CONFIG_VARIABLE = "conf";
    private static final String DEFAULT_PATH = "conf.setting"; //默认classpath下的文件配置
    private static Runnable reload = null;

    private Conf(){
    }

    static class Single{
        private final static Conf conf = loadConf();
    }

    public static Conf get(){
        return Single.conf;
    }

    private static Conf loadConf(){
        Conf conf = new Conf();
        //从系统变量中获取指定全局配置的路径（启动参数）
        String path = System.getProperty(CONFIG_VARIABLE,DEFAULT_PATH);
        conf.init(ResourceUtil.getResourceObj(path), conf.charset, true);
        //监听变化自动重载
        conf.autoLoad(true,(success) ->{
            if(success){
                Debug.setDebug(conf.getBool("debug",false));
                if(reload != null){
                    reload.run();
                }
            }
        });
        Debug.setDebug(conf.getBool("debug",false));
        return conf;
    }

    public String getAbsolutePath(String variableKey, String defaultPath) {
        return FileUtil.getAbsolutePath(getStr(variableKey, defaultPath));
    }

    public String getAbsolutePath(String variableKey) {
        return FileUtil.getAbsolutePath(getStr(variableKey));
    }

    public static void setReload(Runnable reload){
        Conf.reload = reload;
    }
}
